//
//  QuanlityViewController.m
//  MyProject
//
//  Created by dllo on 15/10/30.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//
#import "QuanlityViewController.h"
#import "HandleData.h"
#import <UIImageView+WebCache.h>
#import "QunalityMessage.h"
#import "QunalityGoods.h"
#import "QunalityDetaileTableViewCell.h"
#import <MBProgressHUD.h>
#import "Collect+CoreDataProperties.h"
#import "QuanlitytopicDetilViewController.h"
#import "DataBase.h"
#import "QTableViewCell.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDKUI.h>
#define widtht self.view.bounds.size.width
#define heigh self.view.bounds.size.height


@interface QuanlityViewController ()<UITableViewDataSource, UITableViewDelegate , MBProgressHUDDelegate, UIScrollViewDelegate, UISearchBarDelegate>
{
    MBProgressHUD *hud;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *productArr;
@property (nonatomic, strong) QunalityMessage *quna;
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UILabel *titleL;
@property (nonatomic, strong) UILabel *desc;
@end

@implementation QuanlityViewController

- (void)viewWillAppear:(BOOL)animated
{
    
    self.tabBarController.tabBar.hidden = NO;
    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"isWhite"]) {
        self.tableView.backgroundColor = [UIColor grayColor];
        self.desc.textColor = [UIColor whiteColor];
            self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
        
    }else
    {
        self.tableView.backgroundColor = [UIColor whiteColor];
        self.navigationController.navigationBar.barTintColor = [UIColor redColor];
        
        self.desc.textColor = [UIColor grayColor];
        
    }
    [self.tableView reloadData];
    
}




- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"精品";
    self.view.backgroundColor = [UIColor whiteColor];
    [self handleData];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 49) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    
    [self.tableView registerClass:[QunalityDetaileTableViewCell class] forCellReuseIdentifier:@"desc"];
    
    self.tableView.showsVerticalScrollIndicator = NO;
    
    

    
    hud = [[MBProgressHUD alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:hud];

    [hud show:YES];

    hud.mode = UIPushBehaviorModeContinuous;
    hud.detailsLabelText = @"网络加载中";
    
    
    
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];
    button1.frame = CGRectMake(self.view.bounds.size.width - 50, -40, 40, 40);
    
    [button1 setTitle:@"分享" forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(share:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button1];
    button1.tag = 100;
    button1.layer.cornerRadius = self.view.bounds.size.width/16;
    button1.backgroundColor = [UIColor redColor];
     [button1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeSystem];
    button2.frame = CGRectMake(self.view.bounds.size.width - 50, -40, 40, 40);
    
    [button2 setTitle:@"收藏" forState:UIControlStateNormal];
    [button2 addTarget:self action:@selector(collection:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button2];
    button2.tag = 101;
    button2.layer.cornerRadius = self.view.bounds.size.width/16;
    button2.backgroundColor = [UIColor redColor];
     [button2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    
    
    
    UIButton *button3 = [UIButton buttonWithType:UIButtonTypeSystem];
    button3.frame = CGRectMake(self.view.bounds.size.width - 50,-40, 40, 40);
    
    [button3 setTitle:@"取消" forState:UIControlStateNormal];
    [button3 addTarget:self action:@selector(cancle) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button3];
    button3.tag = 102;
    button3.layer.cornerRadius = self.view.bounds.size.width/16;
    button3.backgroundColor = [UIColor redColor];
    [button3 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"me.png"] style:UIBarButtonItemStylePlain target:self action:@selector(click:)];
    
    
    

}



- (void)share:(UIButton *)btn
{
    // 1.创建分享参数
    NSMutableDictionary *shareParames = [NSMutableDictionary dictionary];
    
    if (self.topic != nil) {
        
        [shareParames SSDKSetupShareParamsByText:self.topic.title images:@[self.topic.pic] url:nil title:@"分享" type:SSDKContentTypeImage];
    }
    
    //进行分享
    [ShareSDK showShareActionSheet:btn items:nil
                       shareParams:shareParames
               onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                   switch (state) {
                       case SSDKResponseStateBegin:
                       {
                           NSLog(@"开始分享");
                       }
                           break;
                       case SSDKResponseStateSuccess:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                               message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                       }
                           break;
                       case SSDKResponseStateFail:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                       }
                           break;
                       case SSDKResponseStateCancel:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享取消"
                                                                               message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                       }
                           break;
                       default:
                           break;
                   }
               }];
}

- (void)collection:(UIButton *)btn
{
    DataBase *date = [DataBase dataBase];
    
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Collect"];
    NSArray *arr = [date.managedObjectContext executeFetchRequest:request error:nil];
    NSMutableArray *array = [NSMutableArray array];
    for (Collect *coll in arr) {
        [array addObject:coll.nameId];
    }
    
    
    if (![array containsObject:self.topic.ID]) {
        
    
    
    Collect *collect = [NSEntityDescription insertNewObjectForEntityForName:@"Collect" inManagedObjectContext:date.managedObjectContext];
    collect.title = self.topic.title;
    collect.nameId = self.topic.ID;
    collect.photo = self.topic.pic;
    [date saveContext];
        
       
        UIAlertController *aler = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏成功" preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:aler animated:YES completion:^{
            
        }];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [aler addAction:action];
        
    }else{
        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"你已经收藏过了" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alertView animated:YES completion:^{
            
        }];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertView addAction:action];
    }

}





- (void)click:(UIButton *)btn
{
    UIButton *button = (UIButton *)[self.view viewWithTag:100];
    UIButton *button1 = (UIButton *)[self.view viewWithTag:101];
    UIButton *button2 = (UIButton *)[self.view viewWithTag:102];
    if (button) {
        
        [UIView animateWithDuration:0.4 animations:^{
            button.frame = CGRectMake(self.view.bounds.size.width - 50, 70, 40, 40);
        }];
    }
    if (button1) {
        
        [UIView animateWithDuration:0.5 animations:^{
            button1.frame = CGRectMake(self.view.bounds.size.width - 50, 120, 40, 40);;
        }];
    }
    if (button2) {
        
        [UIView animateWithDuration:0.6 animations:^{
            button2.frame = CGRectMake(self.view.bounds.size.width - 50,170, 40, 40);;
        }];
    }

}

- (void)cancle
{
    UIButton *button = (UIButton *)[self.view viewWithTag:100];
    UIButton *button1 = (UIButton *)[self.view viewWithTag:101];
    UIButton *button2 = (UIButton *)[self.view viewWithTag:102];
    if (button) {
        
        [UIView animateWithDuration:0.6 animations:^{
            button.frame = CGRectMake(self.view.bounds.size.width - 50, -40, 40, 40);
        }];
    }
    if (button1) {
        
        [UIView animateWithDuration:0.5 animations:^{
            button1.frame = CGRectMake(self.view.bounds.size.width - 50, -40, 40, 40);;
        }];
    }
    if (button2) {
        
        [UIView animateWithDuration:0.4 animations:^{
            button2.frame = CGRectMake(self.view.bounds.size.width - 50,-40, 40, 40);;
        }];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    
    
    
    UIButton *button = (UIButton *)[self.view viewWithTag:100];
    UIButton *button1 = (UIButton *)[self.view viewWithTag:101];
    UIButton *button2 = (UIButton *)[self.view viewWithTag:102];
    if (button) {
        
        [UIView animateWithDuration:0.4 animations:^{
            button.frame = CGRectMake(self.view.bounds.size.width - 50, 70, 40, 40);
        }];
    }
    if (button1) {
        
        [UIView animateWithDuration:0.5 animations:^{
            button1.frame = CGRectMake(self.view.bounds.size.width - 50, 120, 40, 40);;
        }];
    }
    if (button2) {
        
        [UIView animateWithDuration:0.6 animations:^{
            button2.frame = CGRectMake(self.view.bounds.size.width - 50,170, 40, 40);;
        }];
    }
    
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    [self cancle];
}






- (void)handleData
{
    
    


    
    
    NSString *str = [NSString stringWithFormat:@"http://open4.bantangapp.com/topic/info?client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=1115876&oauth_token=08e623418ebf12fe438fb9eed5d176da&track_deviceid=864516020760583&track_device_info=SM701&channel_name=UMENG_CHANNEL&app_installtime=1438818737013&app_versions=4.1.1&os_versions=4.4.2&screensize=1080&v=6&id=%@&oauth_token=08e623418ebf12fe438fb9eed5d176da&screensize=1080&statistics_uv=1", self.ID];
    
    [HandleData handleDataWithUrl:str completion:^(id data) {
        NSDictionary *dic = [data objectForKey:@"data"];
        self.quna = [[QunalityMessage alloc] init];
        [self.quna setValuesForKeysWithDictionary:dic];
        
        
        
        
        self.productArr = [NSMutableArray array];
        NSArray *arr = self.quna.product;
        for (NSDictionary *dic in arr) {
            QunalityGoods *qunality = [[QunalityGoods alloc] init];
            [qunality setValuesForKeysWithDictionary:dic];
            [self.productArr addObject:qunality];
        }
        
        if (self.productArr.count != 0) {
            [hud removeFromSuperview];
        }
        
        [self.tableView reloadData];
        [self headV];
        
    }];
    
    
    
    
    
}

- (void)headV
{
    
    self.tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, widtht, heigh / 2)];
    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.tableHeaderView.bounds.size.width, self.tableView.tableHeaderView.bounds.size.height / 2 )];
    [self.tableView.tableHeaderView addSubview:img];
    
    [img sd_setImageWithURL:[NSURL URLWithString:self.quna.pic ] placeholderImage:[UIImage imageNamed:@"lovebeijing.png"]];
    self.titleL = [[UILabel alloc] initWithFrame:CGRectMake(5, self.tableView.tableHeaderView.bounds.size.height / 8 * 3, widtht - 10, 40)];
    [self.tableView.tableHeaderView addSubview:self.titleL];
    self.titleL.text = self.quna.title;
    self.titleL.textColor = [UIColor whiteColor];
    
    self.desc = [[UILabel alloc] initWithFrame:CGRectMake(5, self.tableView.tableHeaderView.bounds.size.height / 2 + 10, widtht - 10, self.tableView.tableHeaderView.bounds.size.height / 2 - 10)];
    [self.tableView.tableHeaderView addSubview:self.desc];
    
    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"isWhite"]) {
        self.desc.textColor = [UIColor whiteColor];
    }else{
        self.desc.textColor = [UIColor grayColor];
    }
    
    self.desc.font = [UIFont systemFontOfSize:15];
    self.desc.text = self.quna.desc;
    self.desc.numberOfLines = 0;
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    if (tableView.tag == 200) {
        return 10;
    }else{
    return self.productArr.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    QunalityDetaileTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"desc"];
    
    
    QunalityGoods *goods = [self.productArr objectAtIndex:indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    cell.number.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@.png", goods.number]];
    cell.title.text = goods.title;
    cell.desc.text = goods.desc;
    [cell.pic sd_setImageWithURL:[NSURL URLWithString:[[goods.pic objectAtIndex:0] objectForKey:@"pic"]] placeholderImage:[UIImage imageNamed:@"lovebeijing.png"]];
    cell.price.text = [NSString stringWithFormat:@"￥%@", goods.price];
    
       if (![[NSUserDefaults standardUserDefaults]boolForKey:@"isWhite"]) {
        cell.title.textColor = [UIColor whiteColor];
        cell.desc.textColor = [UIColor whiteColor];
        cell.price.textColor = [UIColor whiteColor];
  
    }else
    {
        cell.title.textColor = [UIColor blackColor];
        cell.desc.textColor = [UIColor grayColor];
        cell.price.textColor = [UIColor grayColor];
    
    }
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 520;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    QuanlitytopicDetilViewController *quanlityTopicVC = [[QuanlitytopicDetilViewController alloc] init];
    [self.navigationController pushViewController:quanlityTopicVC animated:YES];
    quanlityTopicVC.goods = [self.productArr objectAtIndex:indexPath.row];
    
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
